package com.ybl.store.backend.service.impl.customer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ybl.store.backend.dao.entity.customer.CustomerVoucherDO;
import com.ybl.store.backend.dao.mapper.customer.CustomerVoucherMapper;
import com.ybl.store.common.constant.VoucherUsageStatus;
import com.ybl.store.common.convention.errorcode.BaseErrorCode;
import com.ybl.store.common.convention.exception.ClientException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class CustomerVoucherService {

    private final CustomerVoucherMapper customerVoucherMapper;

    public void set(Long customerId, Long voucherId, String serial, Integer usageStatus) {
        CustomerVoucherDO customerVoucherDO = get(customerId, voucherId, serial);
        customerVoucherDO.setUsageStatus(usageStatus);
        int result = customerVoucherMapper.updateById(customerVoucherDO);
        if (result < 1) {
            throw new ClientException(BaseErrorCode.CUSTOMER_VOUCHER_ERROR);
        }
    }

    public void del(Long customerId, Long voucherId, String serial) {
        CustomerVoucherDO customerVoucherDO = get(customerId, voucherId, serial);
        int result = customerVoucherMapper.deleteById(customerVoucherDO);
        if (result < 1) {
            throw new ClientException(BaseErrorCode.CUSTOMER_VOUCHER_ERROR);
        }
    }

    private CustomerVoucherDO get(Long customerId, Long voucherId, String serial) {
        LambdaQueryWrapper<CustomerVoucherDO> lambdaQueryWrapper = Wrappers.lambdaQuery(CustomerVoucherDO.class)
                .eq(CustomerVoucherDO::getCustomerId, customerId)
                .eq(CustomerVoucherDO::getVoucherId, voucherId)
                .eq(CustomerVoucherDO::getSerial, serial);
        CustomerVoucherDO customerVoucherDO = customerVoucherMapper.selectOne(lambdaQueryWrapper);
        if (customerVoucherDO == null) {
            customerVoucherDO = new CustomerVoucherDO();
            customerVoucherDO.setCustomerId(customerId);
            customerVoucherDO.setVoucherId(voucherId);
            customerVoucherDO.setSerial(serial);
            customerVoucherDO.setUsageStatus(VoucherUsageStatus.unused);
            int result = customerVoucherMapper.insert(customerVoucherDO);
            if (result < 1) {
                throw new ClientException(BaseErrorCode.CUSTOMER_VOUCHER_ERROR);
            }
        }
        return customerVoucherDO;
    }
}
